from core.tools.func_utils import geodistance
from .models import ChannelRiseInPrice


def distance_sorted(json_list, position):
    """
    距离排序
    :param response:
    :param oliNo: 油号
    :param position: xx,xx
    :return:
    """
    dis_list = []  # 距离容器
    gas_ids = []
    lng1, lat1 = position.split(",")
    for i in json_list:
        dis = geodistance(float(lng1), float(lat1), i.get("gasAddressLongitude"), i.get("gasAddressLatitude"))
        dis_list.append(dis)
        gas_ids.append(i.get("gasId"))
    # 将加油站id 和需要排序的距离做zip
    gas_dis_dict = dict(zip(gas_ids, dis_list))
    # 将距离做排序
    dis_sort = sorted(dis_list)
    # 根据排序的价格找到gasid
    gas_dis_sort = gas_ids
    for gas, dis in gas_dis_dict.items():
        dis_index = dis_sort.index(float(dis))
        gas_dis_sort[dis_index] = gas  # 替换排序
    # 根据gasid排序加油站信息
    gas_info_list_sort = []
    for gas_id in gas_dis_sort:
        for gas_info in json_list:
            if gas_info.get("gasId") == gas_id:
                gas_info_list_sort.append(gas_info)
                break
    return gas_info_list_sort


def price_sorted_by_custom(json_list):
    """
    :param json_list:
    :return:
    """
    # 按照油号找到价格
    price_list = []
    gas_ids = []
    for i in json_list:
        price_list.append(float(i.get("priceYfq")))
        gas_ids.append(i.get("gasId"))
    # 将加油站id 和需要的油号价格做zip
    gas_price_zip = dict(zip(gas_ids, price_list))
    price_sort = sorted(price_list)
    # 根据排序的价格找到gasid
    gas_price_sort = gas_ids
    for gas, price in gas_price_zip.items():
        price_index = price_sort.index(float(price))
        gas_price_sort[price_index] = gas
    # 根据gasid排序加油站信息
    gas_info_list_sort = []
    for gas_id in gas_price_sort:
        for gas_info in json_list:
            if gas_info.get("gasId") == gas_id:
                gas_info_list_sort.append(gas_info)
                break
    return gas_info_list_sort


# 计算价格
def compute_price_by_channel(channel, priceYfq, priceGun):
    priceYfq = float(priceYfq)
    priceGun = float(priceGun)
    rise_in_price = channel.channelriseinprice
    middle_value = 0
    middle_up = 0
    middle_down = 0
    if rise_in_price:
        middle_value = rise_in_price.middle_value
        middle_up = rise_in_price.middle_up
        middle_down = rise_in_price.middle_down
    if priceGun - priceYfq > middle_value:
        priceYfq += middle_up
    else:
        priceYfq += middle_down
    return priceYfq


# 动态获取过来整理数据
def in_time_update_oil(data, oilNo):
    """
    :param data: response.get("result")
    :param channel: 渠道对象
    :return: 整理好前端的数据
    """
    context = []
    from .models import GasStationInfo
    for i in data:
        gasId = i.get("gasId")
        gas_instance = GasStationInfo.objects.get(gasId=gasId)
        oilPriceList = i.get("oilPriceList")
        data = dict()
        data["gasAddress"] = gas_instance.gasAddress
        data["gasLogoBig"] = gas_instance.gasLogoBig
        data["gasLogoSmall"] = gas_instance.gasLogoSmall
        data["gasAddressLongitude"] = gas_instance.gasAddressLongitude
        data["gasAddressLatitude"] = gas_instance.gasAddressLatitude
        data["gasId"] = gas_instance.gasId
        data["gasName"] = gas_instance.gasName
        for oil in oilPriceList:
            priceYfq = float(oil.get("priceYfq")) + 0  # 加7分钱
            priceOfficial = float(oil.get("priceOfficial"))
            priceGun = float(oil.get("priceGun"))
            # 价格比油站便宜
            discount = priceGun - priceYfq > 0
            # 价格比国际价便宜
            official_discount = priceOfficial - priceYfq > 0
            # 过滤油号，只有存在此油号的加油站才放进去
            is_oilNo = str(oil.get("oilNo")) == str(oilNo)
            # 小于加油站油枪价
            less_than_gun = priceYfq < priceGun * 0.98  # 98折
            if less_than_gun and is_oilNo and discount and official_discount:
                data["priceYfq"] = oil.get("priceYfq")
                data["oilNo"] = oil.get("oilNo")
                data["priceGun"] = oil.get("priceGun")
                data["priceOfficial"] = oil.get("priceOfficial")
                context.append(data)  # 才放进去
    return context


# 根据用户手机号动态获取价格(提交订单要根据此价格提交)
def get_actual_time_price(gasIds, mobile, gunNo, czb_api):
    """
    :param gasIds: 加油站id
    :param mobile: 用户手机号
    :param gunNo: 枪号
    :param channel: 渠道对象
    :return:
    """
    response = czb_api.query_price_by_phone(gasIds, mobile)
    if response.get("code") == 200 or response.get("code") == "200":
        result = response.get("result")
        gun = False
        for oilNo in result:  # 油号列表
            oilPriceList = oilNo.get("oilPriceList")
            for gun in oilPriceList:
                if {"gunNo": int(gunNo)} in gun.get("gunNos"):
                    break
        priceYfq = gun.get("priceYfq")
        data = {"priceYfq": priceYfq, "oilName": gun.get("oilName"), "priceGun": gun.get("priceGun"),
                "response": response}
        return data
    else:
        return response.get("message")


# 获取用户对应车主邦渠道是否已经注册过
def get_czb_channel_auth(user, czb_api, channel_key="youpinhuiyuan"):
    if user.czb_channel_auth.exists():
        pass
    else:
        token = czb_api.get_token_from_mc(user.mobile)
        if token:
            user.czb_channel_auth.add(ChannelRiseInPrice.objects.get(channel__app_key=channel_key))
        else:
            content = {"errmsg": "注册失败，请刷新重试"}
            return content

# if hasattr(user, "userprofileextend"):
#     if user.userprofileextend.czb_auth:
#         pass
#     else:
#         token = czb_api.get_token_from_mc(user.mobile)
#         if token:
#             user.userprofileextend.czb_auth = True
#             user.userprofileextend.save()
#         else:
#             content = {"errmsg": "注册失败，请刷新重试"}
#             return Response(content, status=status.HTTP_400_BAD_REQUEST)
# else:
#     token = czb_api.get_token_from_mc(user.mobile)
#     if token:
#         UserProfileExtend.objects.create(user=user, czb_auth=True)
#     else:
#         content = {"errmsg": "注册失败，请刷新重试"}
#         return Response(content, status=status.HTTP_400_BAD_REQUEST)
